package com.example.cd5160866.urlapp.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.http.HttpResponseCache;
import android.os.Environment;
import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUtil {
    private static final int BUFFER_SIZE = 4096;

    public static File getAutoCacheDir(Context context) {
        if (isSDCardMounted())
            return context.getExternalCacheDir();
        String rootDir = getExternalSdCardPath();
        if (!TextUtils.isEmpty(rootDir)) {
            File cache = new File(rootDir, context.getPackageName() + "/cache/");
            if (!cache.exists())
                cache.mkdirs();
            return cache.getAbsoluteFile();
        }
        return context.getCacheDir();
    }

    public static File getAutoCacheDir(String subDir) {
        File cache = new File(getAutoCacheDir(Container.getContext()), subDir);
        if (!cache.exists())
            cache.mkdirs();
        return cache;
    }

    private static boolean isSDCardMounted() {
        return Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
    }

    public static boolean hasOneSDCardMounted() {
        return !TextUtils.isEmpty(getExternalSdCardPath());
    }

    @TargetApi(14)
    public static void picassoDiskCache(Context context) {
        File httpCacheDir = new File(getAutoCacheDir(context), "picasso-cache");
        long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
        try {
            HttpResponseCache.install(httpCacheDir, httpCacheSize);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void store(File file, byte[] data) throws IOException {
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data);
        fos.close();
    }

    /**
     * 获取扩展SD卡存储目录
     * <p/>
     * 如果有外接的SD卡，并且已挂载，则返回这个外置SD卡目录 否则：返回内置SD卡目录
     *
     * @return
     */
    public static String getExternalSdCardPath() {

        if (isSDCardMounted()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }

        String path = null;

        ArrayList<String> devMountList = getDevMountList();

        for (String devMount : devMountList) {
            File file = new File(devMount);

            if (file.isDirectory() && file.canWrite()) {
                path = file.getAbsolutePath();

                String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss")
                        .format(new Date());
                File testWritable = new File(path, "test_" + timeStamp);

                if (testWritable.mkdirs()) {
                    testWritable.delete();
                } else {
                    path = null;
                }
            }
        }
        return path;
    }

    /**
     * 遍历 "system/etc/vold.fstab” 文件，获取全部的Android的挂载点信息
     *
     * @return
     */
    private static ArrayList<String> getDevMountList() {
        String[] toSearch = file2String("/etc/vold.fstab").split(" ");
        ArrayList<String> out = new ArrayList<String>();
        for (int i = 0; i < toSearch.length; i++) {
            if (toSearch[i].contains("dev_mount")) {
                if (new File(toSearch[i + 2]).exists()) {
                    out.add(toSearch[i + 2]);
                }
            }
        }
        return out;
    }

    //    public static void getFileWithLocalPic(String localFilePath, String newFilePath) throws IOException {
    //        File file=new File(localFilePath);
    ////        DevUtil.d("loadLocalHtml",file.getAbsolutePath()+"-"+file.exists());
    //        Document doc = Jsoup.parse(file, "utf-8");
    //        Elements elements = doc.select("img");
    //        for (final Element element : elements) {
    //            String src = element.attr("src");
    ////            DevUtil.d("loadLocalHtml",src);
    //            if(src!=null&&src.startsWith("http")){
    //                String content=file2String(localFilePath);
    //                String pic="file://" + FileLoader.download(src).getAbsolutePath();
    //                DevUtil.d("loadLocalHtml",pic);
    //                string2File(content.replaceAll(src,pic),newFilePath);
    //            }
    //        }
    ////        DevUtil.d("loadLocalHtml",doc.toString());
    //    }
    public static void replaceContentInFile(String replaceFrom, String replaceTo, String filePath) {
        String content = file2String(filePath);
        string2File(content.replaceAll(replaceFrom, replaceTo), filePath);
    }

    public static void string2File(String data, String filePath) {
        FileOutputStream e = null;
        try {
            e = new FileOutputStream(filePath);
            e.write(data.getBytes());
            e.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

    public static String file2String(String filePath) {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(
                    filePath)));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        } catch (Exception e) {
        } finally {
            try {
                in.close();
            } catch (Exception e2) {
            }
        }
        return "";
    }

    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }

    /**
     * Unzip a zip file.  Will overwrite existing files.
     *
     * @param zipFile  Full path of the zip file you'd like to unzip.
     * @param location Full path of the directory you'd like to unzip to (will be created if it doesn't exist).
     * @throws IOException
     */
    public static List<String> unzip(String zipFile, String location) throws IOException {
        int size;
        List<String> list = new ArrayList<String>();
        byte[] buffer = new byte[BUFFER_SIZE];

        try {
            if (!location.endsWith("/")) {
                location += "/";
            }
            File f = new File(location);
            if (!f.isDirectory()) {
                f.mkdirs();
            }
            ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile), BUFFER_SIZE));
            try {
                ZipEntry ze = null;
                while ((ze = zin.getNextEntry()) != null) {
                    String path = location + ze.getName();
                    //                    list.add("file://" + path);
                    list.add(path);
                    File unzipFile = new File(path);

                    if (ze.isDirectory()) {
                        if (!unzipFile.isDirectory()) {
                            unzipFile.mkdirs();
                        }
                    } else {
                        // check for and create parent directories if they don't exist
                        File parentDir = unzipFile.getParentFile();
                        if (null != parentDir) {
                            if (!parentDir.isDirectory()) {
                                parentDir.mkdirs();
                            }
                        }

                        // unzip the file
                        FileOutputStream out = new FileOutputStream(unzipFile, false);
                        BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
                        try {
                            while ((size = zin.read(buffer, 0, BUFFER_SIZE)) != -1) {
                                fout.write(buffer, 0, size);
                            }

                            zin.closeEntry();
                        } finally {
                            fout.flush();
                            fout.close();
                        }
                    }
                }
            } finally {
                zin.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static String getAppCash() {
        return getAutoCacheDir("/dada").getAbsolutePath();
    }

    public static void clearAppCash() {
        File file = new File(getAppCash());
        if (file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0, size = files.length; i < size; i++) {
                files[i].delete();
            }
        }
    }

    /**
     * 复制文件
     *
     * @param srcFile
     * @param destFile
     */
    public static void copy(File srcFile, File destFile) {
        int byteread = 0; // 读取的字节数
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[4096];

            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存bitmap到文件
     *
     * @param bitmap
     * @param path     文件目录路径
     * @param fileName 文件名
     * @param lisetner 结果监听
     */

    public static void saveBitmapAsFile(Bitmap bitmap, String path, String fileName, OnSaveLisetner lisetner) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            String finalPath = file.getAbsoluteFile() + "/" + fileName + ".png";
            FileOutputStream outputStream = new FileOutputStream(finalPath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            outputStream.close();
            lisetner.onSuccess(finalPath);
        } catch (FileNotFoundException e) {
            lisetner.onFiled();
            e.printStackTrace();
        } catch (IOException e) {
            lisetner.onFiled();
            e.printStackTrace();
        }

    }

    public interface OnSaveLisetner {
        void onSuccess(String url);

        void onFiled();
    }
}
